import type { ProFormInstance } from '@ant-design/pro-components';
import { ProFormText, ModalForm } from '@ant-design/pro-components';
import { Button, message } from 'antd';
import { useRef, useState, useMemo, cloneElement } from 'react';

import { modifyPassword } from '@/services/user';

interface IModifyPasswordProps {
  triggerShow?: boolean;
  trigger?: JSX.Element;
  triggerProps?: Record<string, any>;
  defaultFormParams?: Pick<API.ModifyPasswordParams, 'id'> & Record<string, any>;
}

const ModifyPassword: React.FC<IModifyPasswordProps> = (props) => {
  const {
    triggerShow = true,
    trigger,
    triggerProps,
    defaultFormParams = {} as Pick<API.ModifyPasswordParams, 'id'> & Record<string, any>,
  } = props;

  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const formRef = useRef<ProFormInstance>();

  const TriggerDom = useMemo(() => {
    if (!trigger) {
      return null;
    }

    return cloneElement(trigger, {
      key: 'trigger',
      ...trigger.props,
      onClick: async (e: any) => {
        setModalVisible(true);
        trigger.props?.onClick?.(e);
      },
      ...triggerProps,
    });
  }, [trigger, triggerProps]);

  const onFinishHandle = async (values: API.ModifyPasswordParams) => {
    try {
      const res = await modifyPassword({
        ...defaultFormParams,
        password: values.password,
      });
      if (res.data) {
        message.success('修改成功');
        return true;
      }
      message.error(res.message || '修改失败');
      return false;
    } catch (error) {
      console.log(error);
      message.error('修改失败');
      return false;
    }
  };

  return (
    <ModalForm<API.ModifyPasswordParams>
      title="修改密码"
      formRef={formRef}
      // @ts-ignore
      open={modalVisible}
      trigger={
        triggerShow ? (
          TriggerDom || undefined
        ) : (
          <Button
            type="primary"
            {...triggerProps}
            onClick={() => {
              setModalVisible(true);
            }}
          >
            修改密码
          </Button>
        )
      }
      // onOpenChange={setModalVisible}
      onFinish={onFinishHandle}
    >
      <ProFormText.Password name="password" label="新密码" placeholder="请输入新密码" />

      <ProFormText.Password name="company" label="重复新密码" placeholder="请输入新密码" />
    </ModalForm>
  );
};

export default ModifyPassword;
